package com.situ.crm.rbac.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.crm.bean.pojo.User;
import com.situ.crm.bean.vo.UserLoginVO;
import com.situ.crm.common.utils.JSONResult;
import com.situ.crm.common.utils.JwtUtils;
import com.situ.crm.common.utils.MD5Utils;
import com.situ.crm.rbac.service.IUserService;
import com.situ.crm.security.custom.CustomUserDetails;
import io.swagger.annotations.*;
import io.swagger.util.Json;
import jdk.nashorn.internal.scripts.JS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Gao
 * @since 2022-10-17
 */

// 前后端分离之后，Controller返回的都是Json格式数据
// 后台只给前台提供数据，不存在转发到页面的操作
@Api(tags = "用户管理")//tags:你可以当做这个组的名字
@RestController
@RequestMapping("/rbac/user")
//@CrossOrigin
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;



    // Markdown
    //@RequestMapping(value = "/login", method = RequestMethod.GET)
    //注意：对于swagger不要使用@RequestMapping如果使用要加上method，因为@RequestMapping
    //支持任意请求的方式，swagger会为这个接口生成7中请求方式的接口文档
    //value:可以当做这个接口的简称  notes：接口的详细描述
    @ApiOperation(value = "登录", notes = "输入用户名和密码验证登录是否成功")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })*/
    @PostMapping("/login")
    public JSONResult login(@RequestBody UserLoginVO userLoginVO) {
        System.out.println("UserController.login");
        /*//判断用户名是否存在
        User user = userService.selectByName(userLoginVO.getUsername());
        if (user == null) {
            return JSONResult.error("用户名不存在");
        }
        //判断密码是否正确
        String md5Password = MD5Utils.MD5Encode(userLoginVO.getPassword());
        if (!user.getPassword().equalsIgnoreCase(md5Password)) {
            return JSONResult.error("密码不正确");
        }
        //判断用户是否禁用 status==1
        if (user.getStatus() == 0) {
            return JSONResult.error("该用户已经被禁用");
        }

        //根据id和name生成token字符串，返回给浏览器
        String token = JwtUtils.createToken(user.getId(), user.getName());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return JSONResult.ok("登录成功", map);*/

        UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(userLoginVO.getUsername(),
                userLoginVO.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        if (authentication != null) {
            CustomUserDetails customUserDetails  = (CustomUserDetails) authentication.getPrincipal();
            //将登录后的用户信息存入redis，username作为key
            redisTemplate.opsForHash().put("login", customUserDetails.getUsername(), customUserDetails);
            //根据id和name生成token字符串，返回给客户端调用
            String token = JwtUtils.createToken(customUserDetails.getUser().getId(), customUserDetails.getUser().getName());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return JSONResult.ok("登录成功", map);
        } else {
            return JSONResult.error("登录失败");
        }

    }

    @ApiIgnore
    @GetMapping("/selectAll")
    public JSONResult selectAll() {
        List<User> list = userService.list();
        return JSONResult.ok(list);
    }

    @GetMapping("/info")
    public JSONResult info(HttpServletRequest request) {
        System.out.println("UserController.info");
        String token = request.getHeader("token");
        //从token字符串中获取用户名
        String username = JwtUtils.getUsername(token);
        //根据用户名获取当前用户的权限信息:路由权限routers(目录权限和菜单权限)、按钮权限
        Map<String, Object> map = userService.getUserPermissionInfo(username);
        return JSONResult.ok(map);
    }

    @PostMapping("/logout")
    public JSONResult logout() {
        System.out.println("UserController.logout");
        return JSONResult.ok("退出成功");
    }



    @ApiOperation(value = "分页查询", notes = "根据输入的第几页current，每页有多少条limit，返回分页信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", required = false, defaultValue = "1"),
            @ApiImplicitParam(name = "limit", value = "每页有多少条", required = false, defaultValue = "5")
    })
    @GetMapping("/selectByPage")
    public JSONResult selectByPage(@RequestParam(value = "page", required = false, defaultValue = "1") Integer current,
                                   @RequestParam(value = "limit", required = false, defaultValue = "5") Integer limit) {
        IPage<User> page = new Page<>(current, limit);
        userService.page(page, null);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("list", page.getRecords());

        return JSONResult.ok(map);
    }


    @ApiOperation(value = "删除", notes = "根据id删除员工")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户的id", required = true)
    })
    @PreAuthorize("hasAuthority('rbac:user:delete')")
    @DeleteMapping("/deleteById/{id}")
    public JSONResult deleteById(@PathVariable Long id) {
        boolean isSuccess = userService.removeById(id);
        return isSuccess ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @PostMapping("/add")
    public JSONResult add(@RequestBody User user) {
        boolean isSuccess = userService.save(user);
        return isSuccess ? JSONResult.ok("添加成功") : JSONResult.error("添加失败");
    }

    @GetMapping("/selectById/{id}")
    public JSONResult selectById(@PathVariable Long id) {
        User user = userService.getById(id);
        return JSONResult.ok(user);
    }

    @PutMapping("/update")
    public JSONResult update(@RequestBody User user) {
        boolean isSuccess = userService.updateById(user);
        return isSuccess ? JSONResult.ok("修改成功") : JSONResult.error("修改失败");
    }

    @PutMapping("/updateStatus/{id}/{status}")
    public JSONResult updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        userService.updateStatus(id, status);
        return JSONResult.ok("修改成功");
    }
}

